import {isEmpty} from '../utils'
import os from 'os'
import {
    getToolCacheDir,
    getToolVersionCacheCompleteFilePath,
    getToolVersionCacheDir
} from './cache'
import logging from '../logging'
import fs from 'fs'

export async function which(
    toolName: string,
    toolVersion: string,
    osArch?: string
): Promise<string> {
    if (isEmpty(toolName)) {
        throw new Error("missing 'toolName'")
    }

    if (isEmpty(toolVersion)) {
        throw new Error("missing 'toolVersion'")
    }

    if (isEmpty(osArch)) {
        osArch = os.arch()
    }

    const toolCacheDir: string = getToolVersionCacheDir(
        toolName,
        toolVersion,
        osArch
    )
    const toolCacheCompletedFile: string = getToolVersionCacheCompleteFilePath(
        toolName,
        toolVersion,
        osArch
    )
    logging.debug(
        `Try to load cached tool from ${toolCacheDir}, toolName=${toolName}, toolVersion=${toolVersion}, osArch=${osArch}`
    )
    if (fs.existsSync(toolCacheCompletedFile)) {
        logging.debug(
            `Found the cache tool in ${toolCacheDir}, toolName=${toolName}, toolVersion=${toolVersion}, osArch=${osArch}`
        )
        return toolCacheDir
    } else {
        logging.debug(
            `Can not find the tool, toolName=${toolName}, toolVersion=${toolVersion}, osArch=${osArch}`
        )
        return ''
    }
}

export async function whichAllVersions(
    toolName: string,
    osArch?: string
): Promise<string[]> {
    if (isEmpty(toolName)) {
        throw new Error("missing 'toolName'")
    }
    if (isEmpty(osArch)) {
        osArch = os.arch()
    }

    const cachedToolVersions: string[] = []

    const toolCacheDir: string = getToolCacheDir(toolName)
    if (!fs.existsSync(toolCacheDir)) {
        return cachedToolVersions
    }
    const versionItems: string[] = fs.readdirSync(toolCacheDir)
    for (const versionItem of versionItems) {
        const completeFilePath = getToolVersionCacheCompleteFilePath(
            toolName,
            versionItem,
            osArch
        )
        if (fs.existsSync(completeFilePath)) {
            cachedToolVersions.push(versionItem)
        }
    }
    return cachedToolVersions
}
